package com.example.myapplication.Style;

import com.example.myapplication.Person;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.List;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

public class SAXParserHandler extends DefaultHandler {
  private ArrayList<Person> personList;
  private Person currentPerson;
  private StringBuilder currentValue;
  private boolean parsingName;
  private boolean parsingJob;
  public ArrayList<Person> getPersonList() {
    return personList;
  }

  @Override public void startDocument() throws SAXException {
    super.startDocument();
    personList = new ArrayList<>();

  }

  @Override
  public void startElement(String uri, String localName, String qName, Attributes attributes)
      throws SAXException {
    if (qName.equalsIgnoreCase("person")) {
      currentPerson = new Person();
    } else if (qName.equalsIgnoreCase("name")) {
      parsingName=true;
    } else if (qName.equalsIgnoreCase("job")) {
      parsingJob = true;
    }
    currentValue=new StringBuilder();


  }

  @Override public void characters(char[] ch, int start, int length) throws SAXException {
    currentValue.append(ch, start, length);
  }

  @Override public void endElement(String uri, String localName, String qName) throws SAXException {
    if (parsingName) {
      currentPerson.setName(currentValue.toString());
      parsingName=false;
    }
    else if (parsingJob) {
      currentPerson.setJob(currentValue.toString());
      parsingJob = false;
    } else if (qName.equalsIgnoreCase("person")) {
      personList.add(currentPerson);
      currentPerson=null;
    }
  }

}
